package com.telit.android.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telit.android.dao.AppUserLocationDao;
import com.telit.android.dto.AppLocationDTO;
import com.telit.android.entity.AppUserLocation;
import com.telit.android.service.AppLocationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * @Auther amy
 * @Describe
 */
@Service
public class AppLocationServiceImpl implements AppLocationService {

    @Autowired
    private AppUserLocationDao appUserLocationDao;

    @Override
    public int uploadLocation(AppLocationDTO appLocationDTO) {
        // 查询userId的定位在数据库是否存在
        AppUserLocation location = selectByUserId(appLocationDTO.getUserId());

        // 若定位不存在就新增
        if(location == null){
            synchronized (this) {
                if(location == null) {
                    AppUserLocation appUserLocation = new AppUserLocation();
                    BeanUtils.copyProperties(appLocationDTO, appUserLocation);
                    appUserLocation.setCreateTime(new Date());
                    return appUserLocationDao.insert(appUserLocation);
                }
            }
        }

        // 存在就更新
        location.setLongitude(appLocationDTO.getLongitude());
        location.setLatitude(appLocationDTO.getLatitude());
        location.setUpdateTime(new Date());

        return appUserLocationDao.updateById(location);
    }

    /**
     * 查找在线用户信息
     * 在线：四分钟之内有经纬度的上传
     * 离线：四分钟之内无经纬度上传
     *
     * @return 在线用户
     */
    @Override
    public List<AppUserLocation> onlineList() {
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, -4);
        Date startTime = calendar.getTime();
        LambdaQueryWrapper<AppUserLocation> appUserLocationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserLocationLambdaQueryWrapper.le(AppUserLocation::getUpdateTime, now);
        appUserLocationLambdaQueryWrapper.ge(AppUserLocation::getUpdateTime, startTime);
        return appUserLocationDao.selectList(appUserLocationLambdaQueryWrapper);
    }

    /**
     * 根据用户id查询定位信息是否存在
     *
     * @return
     */
    private AppUserLocation selectByUserId(Long userId) {
        QueryWrapper<AppUserLocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return appUserLocationDao.selectOne(queryWrapper);
    }
}
